package com.crm.api.service.impl;

import com.crm.api.entity.Customer;
import com.crm.api.mapper.CustomerMapper;
import com.crm.api.mapper.EmployeeMapper;
import com.crm.api.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 客户服务实现类
 */
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> getCustomers(Integer page, Integer size, String companyName, 
                                          String contactPerson, String customerLevel, 
                                          String industry, String customerSource, Boolean isActive) {
        
        // 计算偏移量
        Integer offset = (page - 1) * size;
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("offset", offset);
        params.put("pageSize", size);
        params.put("limit", size);  // 为了兼容性保留
        params.put("companyName", companyName);
        params.put("contactPerson", contactPerson);
        params.put("customerLevel", customerLevel);
        params.put("industry", industry);
        params.put("customerSource", customerSource);
        params.put("isActive", isActive);
        
        // 查询数据
        List<Map<String, Object>> customers = customerMapper.findCustomersWithDetails(params);
        Integer total = customerMapper.countCustomers(params);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("data", customers);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (total + size - 1) / size);
        
        return result;
    }

    @Override
    public Customer getCustomerById(Integer id) {
        return customerMapper.findById(id);
    }

    @Override
    public Customer createCustomer(Customer customer, String creatorUsername) {
        // 获取创建人ID
        Integer createdBy = employeeMapper.findByUsername(creatorUsername).getId();
        customer.setCreatedBy(createdBy);
        
        // 生成客户编号
        String customerCode = generateCustomerCode();
        customer.setCustomerCode(customerCode);
        
        // 设置默认值
        if (customer.getIsActive() == null) {
            customer.setIsActive(true); // 默认有效
        }
        
        // 设置创建时间
        customer.setCreatedAt(new Date());
        customer.setUpdatedAt(new Date());
        
        // 插入数据
        customerMapper.insert(customer);
        
        return customer;
    }

    @Override
    public Customer updateCustomer(Customer customer) {
        // 检查客户是否存在
        Customer existingCustomer = customerMapper.findById(customer.getId());
        if (existingCustomer == null) {
            return null;
        }
        
        // 设置更新时间
        customer.setUpdatedAt(new Date());
        
        // 更新数据
        customerMapper.update(customer);
        
        return customerMapper.findById(customer.getId());
    }

    @Override
    public boolean deleteCustomer(Integer id) {
        // 检查客户是否存在
        Customer customer = customerMapper.findById(id);
        if (customer == null) {
            return false;
        }
        
        // 删除客户
        customerMapper.deleteById(id);
        return true;
    }

    @Override
    public Map<String, Object> batchDeleteCustomers(List<Integer> ids) {
        int totalCount = ids.size();
        int successCount = 0;
        int failCount = 0;
        List<String> failReasons = new ArrayList<>();
        
        for (Integer id : ids) {
            try {
                // 检查是否有关联数据
                if (hasRelatedBusinesses(id) || hasRelatedWorkOrders(id)) {
                    failCount++;
                    failReasons.add("客户ID " + id + ": 存在关联的业务或工单");
                    continue;
                }
                
                // 删除客户
                boolean deleted = deleteCustomer(id);
                if (deleted) {
                    successCount++;
                } else {
                    failCount++;
                    failReasons.add("客户ID " + id + ": 客户不存在");
                }
            } catch (Exception e) {
                failCount++;
                failReasons.add("客户ID " + id + ": " + e.getMessage());
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", totalCount);
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        result.put("failReasons", failReasons);
        
        return result;
    }


    @Override
    public Map<String, Object> getCustomerStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 基础统计
        stats.put("totalCount", customerMapper.getTotalCount());
        stats.put("activeCount", customerMapper.getActiveCount());
        stats.put("inactiveCount", customerMapper.getInactiveCount());
        
        // 等级统计
        stats.put("levelStats", customerMapper.getLevelStats());
        
        // 行业统计
        stats.put("industryStats", customerMapper.getIndustryStats());
        
        // 来源统计
        stats.put("sourceStats", customerMapper.getSourceStats());
        
        // 地区统计
        stats.put("provinceStats", customerMapper.getProvinceStats());
        
        // 月度新增统计
        stats.put("monthlyStats", customerMapper.getMonthlyStats());
        
        return stats;
    }

    @Override
    public boolean existsByCompanyName(String companyName) {
        return customerMapper.existsByCompanyName(companyName) > 0;
    }

    @Override
    public boolean existsByCompanyNameAndNotId(String companyName, Integer id) {
        return customerMapper.existsByCompanyNameAndNotId(companyName, id) > 0;
    }

    @Override
    public boolean hasRelatedBusinesses(Integer id) {
        return customerMapper.countRelatedBusinesses(id) > 0;
    }

    @Override
    public boolean hasRelatedWorkOrders(Integer id) {
        return customerMapper.countRelatedWorkOrders(id) > 0;
    }

    /**
     * 生成客户编号
     */
    private String generateCustomerCode() {
        // 获取当前最大编号
        String maxCode = customerMapper.getMaxCustomerCode();
        
        if (maxCode == null) {
            return "CUS001";
        }
        
        // 提取数字部分
        String numberPart = maxCode.substring(3);
        int number = Integer.parseInt(numberPart) + 1;
        
        // 格式化为3位数字
        return String.format("CUS%03d", number);
    }

    /**
     * 获取单元格值作为字符串
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf((long) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}